<?php declare(strict_types=1);
namespace App\Http\Controller\Test;

use App\Exception\ApiException;
use App\Library\Core\ErrCode;
use App\Library\Core\Token;
use Swoft\Http\Message\Request;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;

/**
 * Class AuthController
 *
 * @Controller(prefix="Auth")
 * @package App\Http\Controller\Test
 */
class AuthController extends BaseController
{

    /**
     * 账号注册
     * @RequestMapping("register")
     */
    public function registerAction(Request $request)
    {
        //TODO: 调用user RPC服务，注册用户信息
        $user_id = $this->serviceUser->doRegister((array)$request->input());
        if (!$user_id)
        {
            throw new ApiException(ErrCode::msg(ErrCode::PARAM_REQ_MISSING) ,ErrCode::PARAM_REQ_MISSING );
        }

        return $user_id;
    }

    /**
     * 账号登录
     * @RequestMapping("signin")
     */
    public function signInAction(Request $request)
    {
        $username   = $request->input('username');
        $password   = $request->input('password');
        $openid     = $request->input('openid');

        $params = [
            'username'=>$username,
            'password'=>$password,
            'openid'=>$openid
        ];
        //TODO: 调用user RPC服务，校验登录信息，登录成功后，返回token
        $user = $this->serviceUser->doLogin((array)$params);
        if (!$user['id'])
        {
            throw new ApiException(ErrCode::msg(ErrCode::PARAM_REQ_MISSING) ,ErrCode::PARAM_REQ_MISSING );
        }
        //TODO：校验userInfo
        $params['user_id'] = $user['id'];
        $token = Token::createToken($params);
        return $token;
    }

    /**
     * 生成Token
     * @param Request $request
     * @RequestMapping("generateToken")
     */
    public function generateToken(Request $request)
    {
        $userInfo = $request->input('userInfo');

        if (!$userInfo)
        {
            throw new ApiException(ErrCode::msg(ErrCode::PARAM_REQ_MISSING) ,ErrCode::PARAM_REQ_MISSING );
        }
        //TODO：校验userInfo
        $token = Token::createToken($userInfo);
        return $token;
    }


}